package org.minbox.chapter;

import org.minbox.chapter.entity.PhoneCode;
import org.minbox.chapter.entity.SystemUser;
import org.minbox.chapter.service.PhoneCodeService;
import org.minbox.chapter.service.UserService;
import org.minbox.framework.api.boot.plugin.oauth.exception.ApiBootTokenException;
import org.minbox.framework.api.boot.plugin.oauth.grant.ApiBootOauthTokenGranter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Map;

/**
 * 手机验证码OAuth2的认证方式实现
 *
 * @author 恒宇少年
 * @see ApiBootOauthTokenGranter
 */
@Component
public class PhoneCodeGrantType implements ApiBootOauthTokenGranter {
    /**
     * 手机号验证码方式的授权方式
     */
    private static final String GRANT_TYPE_PHONE_CODE = "phone_code";
    /**
     * 授权参数：手机号
     */
    private static final String PARAM_PHONE = "phone";
    /**
     * 授权参数：验证码
     */
    private static final String PARAM_CODE = "code";
    /**
     * 手机号验证码业务逻辑
     */
    @Autowired
    private PhoneCodeService phoneCodeService;
    /**
     * 系统用户业务逻辑
     */
    @Autowired
    private UserService userService;

    @Override
    public String grantType() {
        return GRANT_TYPE_PHONE_CODE;
    }

    /**
     * 根据自定义的授权参数进行查询用户信息
     *
     * @param parameters
     * @return
     * @throws ApiBootTokenException
     */
    @Override
    public UserDetails loadByParameter(Map<String, String> parameters) throws ApiBootTokenException {
        String phone = parameters.get(PARAM_PHONE);
        String code = parameters.get(PARAM_CODE);
        PhoneCode phoneCode = phoneCodeService.findPhoneCode(phone, code);
        if (ObjectUtils.isEmpty(phoneCode)) {
            throw new ApiBootTokenException("登录失败，验证码：" + code + "，已过期.");
        }
        UserDetails userDetails = userService.findByPhone(phone);
        if (ObjectUtils.isEmpty(userDetails)) {
            throw new ApiBootTokenException("用户：" + phone + "，不存在.");
        }
        return userDetails;
    }
}
